"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 数据库系统
Case Name   : 删除pid文件权限，主机停服，备升主
Create At   : 2020/07/23
@zou_jialiang0505328126
Description :
    1.停止主服务器
    2.删除备机pid文件权限
    3.备机执行failover
    4.恢复pid文件权限
    5.备机执行failover
    6.查询集群状态
    7.创建表，插入数据
    8.还原主备，执行switchover
Expect      :
    1.停止主服务器
    2.删除备机pid文件权限
    3.备机执行failover
    4.恢复pid文件权限
    5.备机执行failover
    6.查询集群状态
    7.创建表，插入数据
    8.还原主备，执行switchover
History     :
    modified：2021-4-22 by 5328113;状态结果查询方式变更，修改脚本；
    modified：2021/02/02  modified by @peilinqian，修改整个脚本逻辑
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import *
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class DbsysCase129(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('----this is setup----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.sta_1_sh = CommonSH('Standby1DbUser')
        self.sta_2_sh = CommonSH('Standby2DbUser')
        self.pri_dbuser = Node(node='PrimaryDbUser')
        self.pri_root = Node(node='PrimaryRoot')
        self.sta1_dbuser = Node(node='Standby1DbUser')
        self.sta1_root = Node(node='Standby1Root')
        self.com = Common()
        self.constant = Constant()
        self.pid_file = os.path.join(macro.DB_INSTANCE_PATH,
                                     macro.DB_POSTMASTER_PID_NAME)
        self.MAX_NUM = 10000
        self.table_test = 't_RTO_Dbsys_Case042'
        self.insert_sql = f'''drop table if exists {self.table_test};
              create table {self.table_test}(id int);
              begin 
              for i in 1..{self.MAX_NUM} loop
              insert into {self.table_test} values(i);
              end loop;
              end;'''
        self.select_sql = f'select count(*) from {self.table_test};'
        self.drop_sql = f'drop table {self.table_test};'

        self.log.info('----Opengauss_Reliability_Dbsys_Case129 start----')

    def test_main(self):
        self.log.info("----1.停止主服务器 ----")
        stop_msg = self.pri_sh.stopDbInstance()
        self.assertIn(self.constant.GS_CTL_STOP_SUCCESS_MSG, stop_msg)

        self.log.info("----2.删除备机pid文件权限 ----")
        chmod_cmd = f'chmod 000 {self.pid_file};ls -al {self.pid_file}'
        chmod_result = self.sta1_dbuser.sh(chmod_cmd).result()
        self.log.info(chmod_result)

        self.log.info('----3.备机failover----')
        assert_msg = self.constant.PERMISSION_DENY_MSG
        failover_result = self.sta_1_sh.executeGsctl('failover', assert_msg)
        self.assertTrue(failover_result)

        self.log.info('----4.恢复pid文件权限----')
        chmod_cmd = f'chmod 600 {self.pid_file};ls -al {self.pid_file}'
        self.sta1_dbuser.sh(chmod_cmd).result()

        self.log.info('----5.备机再次failover----')
        success_msg = self.constant.FAILOVER_SUCCESS_MSG
        switchover_result = self.sta_1_sh.executeGsctl('failover',
                                                       success_msg)
        self.assertTrue(switchover_result)
        refresh_result = self.sta_1_sh.exec_refresh_conf()
        self.assertTrue(refresh_result)

        self.log.info('----备机启动----')
        start_msg = self.pri_sh.startDbInstance('standby')
        self.assertIn(self.constant.RESTART_SUCCESS_MSG, start_msg)

        self.log.info('----查看主机query，同步是否正常----')
        self.sta_1_sh.check_location_consistency('primary', 3)

        self.log.info('----6.查询主备状态----')
        status = self.pri_sh.getDbClusterStatus('status')
        self.assertTrue(status)

        self.log.info('----7.创建数据表，并插入数据功能正常----')
        insert_result = self.sta_1_sh.executDbSql(self.insert_sql)
        self.log.info(insert_result)
        select_result = self.sta_1_sh.executDbSql(self.select_sql)
        self.log.info(select_result)
        self.assertIn(str(self.MAX_NUM), select_result)

        self.log.info('----8.还原主备，执行switchover----')
        success_msg = self.constant.SWITCH_SUCCESS_MSG
        switchover_result = self.pri_sh.executeGsctl('switchover',
                                                     success_msg)
        self.assertTrue(switchover_result)
        refreshconf_result = self.pri_sh.exec_refresh_conf()
        self.assertTrue(refreshconf_result)

        self.log.info('----查看主机query，同步是否正常----')
        self.pri_sh.check_location_consistency('primary', 3)

        self.log.info('----查询主备状态----')
        status = self.pri_sh.getDbClusterStatus('status')
        self.assertTrue(status)

    def tearDown(self):
        self.log.info('--------this is tearDown-------')
        self.log.info('----恢复pid文件权限----')
        chmod_cmd = f'chmod 600 {self.pid_file};ls -al {self.pid_file}'
        self.sta1_dbuser.sh(chmod_cmd).result()

        host_name = self.pri_root.sh('hostname').result()
        if self.pri_sh.check_whether_need_switch(host_name):
            self.log.info('----恢复主备关系----')
            if self.pri_sh.check_whether_need_build():
                self.log.info('如果备机无法恢复，需要重建备机')
                self.pri_sh.executeGsctl('build',
                                         self.constant.REBUILD_SUCCESS_MSG)
            self.log.info('---进行主备切换---')
            success_msg = self.constant.SWITCHOVER_SUCCESS_MSG
            result = self.pri_sh.executeGsctl('switchover', success_msg)
            self.log.info(result)
            result = self.pri_sh.exec_refresh_conf()
            self.log.info(result)

        self.log.info('----Opengauss_Reliability_Dbsys_Case129 执行结束----')
